home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7133 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Link list Vs Memory block
  5. Date: Fri, 16 Feb 96 17:33:05 GMT
  6. Organization: none
  7. Message-ID: <824491985snz@genesis.demon.co.uk>
  8. References: <4g0r86$fk5@netnews.upenn.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4g0r86$fk5@netnews.upenn.edu>
  15.            skramiah@gradine.cis.upenn.edu "Senthil K. Ramiah" writes:
  16.  
  17. >Hi Everyone
  18. >Consider the following program segment.
  19. >
  20. >struct struct_s
  21. >{
  22. >        int i;
  23. >        char c;
  24. >};
  25. >main()
  26. >{
  27. >        struct struct_s *s1;
  28. >
  29. >        s1 = malloc(sizeof(struct struct_s) * 2);
  30.  
  31. You should always test a call to malloc for failure.
  32.  
  33. >        s1->i =1; s1->c ='a';
  34. >        s1++;
  35. >        s1->i =2; s1->c = 'b';
  36. >}
  37. >
  38. >My questions are:
  39. >
  40. >1) How safe is it to use the above method
  41. >   instead of a link list.
  42.  
  43. There is no problem using malloc to allocate arrays (an array of structs
  44. in this case) - it is perfectly safe.
  45.  
  46. >2) Will this implementation work on all platforms.
  47.  
  48. Yes. However make sure you pass the correct pointer value when you
  49. call free. After executing s1++ above you would have to use free(s1-1).
  50. It is a good idea to keep a record of the exact pointer value returned by
  51. malloc.
  52.  
  53. -- 
  54. -----------------------------------------
  55. Lawrence Kirby | fred@genesis.demon.co.uk
  56. Wilts, England | 70734.126@compuserve.com
  57. -----------------------------------------
  58.